package models

import (
	"github.com/jinzhu/gorm"
	"kop/modules/shop/configuration"
	"kop/modules/shop/entity"
	"kop/pb"
)

func CreateGoods(dB *gorm.DB, roleID, goodsID int32) *pb.Goods {

	var conf, err = configuration.GetByGoodsID(goodsID)
	if err != nil {
		panic(err)
	}

	var data = entity.ShopGoods{
		RoleID:  roleID,
		GoodsID: goodsID,
		ShopID:  conf.ShopID,
		BuyNum:  conf.Limit,
	}

	if err := dB.Create(&data).Error; err != nil {
		panic(err)
	}

	return buildPbGoods(data)
}

//func CreateGoodsList(dB *gorm.DB, roleID int32, goodsIDs []int32) []*pb.Goods {
//
//	var data = make([]interface{}, 0, len(goodsIDs)+1)
//
//	for _, goodsID := range goodsIDs {
//		var conf, err = configuration.GetByGoodsID(goodsID)
//		if err != nil {
//			panic(err)
//		}
//
//		data = append(data, entity.ShopGoods{
//			RoleID:  roleID,
//			GoodsID: goodsID,
//			BuyNum:  conf.Limit,
//		})
//	}
//
//	if err := dB.Create(data).Error; err != nil {
//		panic(err)
//	}
//
//	var res = make([]*pb.Goods, 0, len(data))
//	for _, v := range data {
//		res = append(res, buildPbGoods(v.(entity.ShopGoods)))
//	}
//
//	return res
//}

func GetGoodsList(dB *gorm.DB, roleID, shopID int32) []*pb.Goods {

	var data []entity.ShopGoods
	if err := dB.Where("role_id = ? AND shop_id = ?", roleID, shopID).Find(&data).Error; err != nil {
		panic(err)
	}

	var res = make([]*pb.Goods, 0, len(data)+1)
	for _, v := range data {

		res = append(res, buildPbGoods(v))
	}

	return res
}

func GetGoods(dB *gorm.DB, roleID, goodsID int32) (*pb.Goods, error) {

	var e = entity.ShopGoods{
		RoleID:  roleID,
		GoodsID: goodsID,
	}

	if err := dB.First(&e).Error; err != nil {

		if err == gorm.ErrRecordNotFound {
			return nil, err
		}

		panic(err)
	}

	return buildPbGoods(e), nil
}

func SaveGoods(dB *gorm.DB, roleID int32, goods *pb.Goods) {

	var e = entity.ShopGoods{
		RoleID:  roleID,
		ShopID:  goods.ShopID,
		GoodsID: goods.GoodsID,
		Group:   goods.Group,
		BuyNum:  goods.BuyNum,
	}

	if err := dB.Save(&e).Error; err != nil {
		panic(err)
	}

	*goods = *buildPbGoods(e)
}

func DelGoodsByShopID(dB *gorm.DB, roleID, shopID int32) {

	var data entity.ShopGoods
	if err := dB.Delete(&data, "role_id = ? AND shop_id = ?", roleID, shopID).Error; err != nil {
		panic(err)
	}
}

func DelGoodsByGoodsID(dB *gorm.DB, roleID, goodsID int32) {

	var data = entity.ShopGoods{RoleID: roleID, GoodsID: goodsID}

	if err := dB.Delete(&data).Error; err != nil {
		panic(err)
	}
}

func buildPbGoods(e entity.ShopGoods) *pb.Goods {

	var conf, err = configuration.GetByGoodsID(e.GoodsID)
	if err != nil {
		panic(err)
	}

	return &pb.Goods{
		GoodsID:   e.GoodsID,
		ShopID:    e.ShopID,
		PropID:    conf.PropID,
		Number:    conf.Number,
		BuyNum:    e.BuyNum,
		BuyMaxNum: conf.Limit,
		NeedItem:  &pb.RawItem{ItemID: conf.NeedItemID, Number: conf.Price},
		Group:     e.Group,
		Level:     conf.Level,
		VIP:       conf.Vip,
	}
}
